package cn.cloud9.designpattern.dp01singleton;

/**
 * @author OnCloud9
 * @description
 * @project Java
 * @date 2022年05月22日 16:38
 */
public class Singleton11 {

    private final static ThreadLocal<Singleton11> TREAD_LOCAL_INSTANCE = ThreadLocal.withInitial(() -> new Singleton11());

    private Singleton11() {}

    public static ThreadLocal<Singleton11> getTreadLocalInstance() {
        return TREAD_LOCAL_INSTANCE;
    }

    public static void main(String[] args) {
        final ThreadLocal<Singleton11> tli1 = Singleton11.getTreadLocalInstance();
        final ThreadLocal<Singleton11> tli2 = Singleton11.getTreadLocalInstance();
        final ThreadLocal<Singleton11> tli3 = Singleton11.getTreadLocalInstance();

        System.out.println(tli1);
        System.out.println(tli2);
        System.out.println(tli3);

        class ThreadLocalTest implements Runnable {
            @Override
            public void run() {
                final ThreadLocal<Singleton11> tli = Singleton11.getTreadLocalInstance();
                System.out.println(Thread.currentThread().getName() + ":" + tli);
            }
        }

        final Thread thread1 = new Thread(new ThreadLocalTest());
        final Thread thread2 = new Thread(new ThreadLocalTest());
        final Thread thread3 = new Thread(new ThreadLocalTest());
        thread1.start();
        thread2.start();
        thread3.start();
    }
}
